package com.jh.fcsm.controller.sys;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jh.fcsm.beans.sys.SysFileInfo;
import com.jh.fcsm.beans.sys.vo.SystemFileinfoVo;
import com.jh.fcsm.common.BaseController;
import com.jh.fcsm.common.RestApiResponse;
import com.jh.fcsm.common.annotation.OperLogAnnotation;
import com.jh.fcsm.common.annotation.RepeatSubAnnotation;
import com.jh.fcsm.common.annotation.SystemLogAnnotation;
import com.jh.fcsm.common.exception.ServiceException;
import com.jh.fcsm.config.FileServiceFactory;
import com.jh.fcsm.constant.Constant;
import com.jh.fcsm.dao.sys.SysFileInfoMapper;
import com.jh.fcsm.service.sys.FileService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import java.util.List;

@RestController
@RequestMapping("/sys/file")
public class FileController extends BaseController {

    private static final String PER_PREFIX = "btn:sys:file:";
    @Autowired
    private FileServiceFactory fileServiceFactory;
    @Autowired
    private SysFileInfoMapper fileInfoMapper;

    @Value("${file.useFileType}")
    private String fileSource;

    /**
     * 文件上传<br>
     * 根据fileSource选择上传方式，目前仅实现了上传到本地<br>
     * 如有需要可上传到第三方，如阿里云、七牛等
     *
     * @param file 文件
     * @throws Exception 异常
     */
    @PostMapping("/upload")
    public SysFileInfo upload(@RequestParam("file") MultipartFile file) throws Exception {
        FileService fileService = fileServiceFactory.getFileService(fileSource);
        //查询当前用户的组织信息 szx增加
        SysFileInfo fileInfo = new SysFileInfo();
        return fileService.upload(file, fileInfo);
    }

    /**
     * 文件批量删除
     *
     * @param ids 文件IDs
     */
    @RepeatSubAnnotation
    @PostMapping(value = "/deleteFile")
    @ApiOperation(value = "批量删除", notes = "批量删除文件")
    @PreAuthorize("hasAuthority('" + PER_PREFIX + "batch:del')")
    @SystemLogAnnotation(type = "文件查询", value = "批量删除文件")
    public RestApiResponse<?> deleteRole(@RequestBody List<String> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            throw new ServiceException("非法请求");
        }
        SysFileInfo fileInfo = null;
        for (String id : ids) {
            fileInfo = fileInfoMapper.selectByPrimaryKey(id);
            if (fileInfo != null) {
                FileService fileService = fileServiceFactory.getFileService(fileInfo.getSource());
                fileService.delete(fileInfo);
            }
        }
        return RestApiResponse.ok();
    }

    /**
     * 文件删除
     *
     * @param id 文件ID
     */
    @RepeatSubAnnotation
    @GetMapping("/delete/{id}")
    @ApiOperation(value = "文件查询", notes = "删除单个文件")
    @PreAuthorize("hasAuthority('" + PER_PREFIX + "del')")
    @SystemLogAnnotation(type = "文件查询", value = "删除单个文件")
    @OperLogAnnotation(value = "'批量删除文件,id:'+#id", module = "基础信息管理", submodule = "文件查询")
    public void delete(@PathVariable String id) {
        SysFileInfo fileInfo = fileInfoMapper.selectByPrimaryKey(id);
        if (fileInfo != null) {
            FileService fileService = fileServiceFactory.getFileService(fileInfo.getSource());
            fileService.delete(fileInfo);
        }
    }

    /**
     * 文件查询
     *
     * @param fileInfo 文件信息
     * @return 结果
     */
    @PostMapping("/findPage")
    @ApiOperation(value = "文件查询", notes = "查询文件列表")
    @PreAuthorize("hasAuthority('" + PER_PREFIX + "query')")
    public RestApiResponse<?> findFiles(@RequestBody SystemFileinfoVo fileInfo) {
        PageHelper.startPage(fileInfo.getPageNum(), fileInfo.getPageSize());
        Example example = new Example(SysFileInfo.class);
        Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(fileInfo.getName())) {
            criteria.andLike("name", "%" + fileInfo.getName() + "%");
        }
        if (!StringUtils.isEmpty(fileInfo.getSource())) {
            criteria.andEqualTo("source", fileInfo.getSource());
        }
        if (!StringUtils.isEmpty(fileInfo.getBeginDate())) {
            criteria.andGreaterThanOrEqualTo("createTime", fileInfo.getBeginDate());
        }
        if (!StringUtils.isEmpty(fileInfo.getEndDate())) {
            criteria.andLessThanOrEqualTo("createTime", fileInfo.getEndDate());
        }
        criteria.andEqualTo("yn", Constant.YES);
        //默认排序
        if (StringUtils.isEmpty(fileInfo.getSortField())) {
            example.orderBy("createTime").desc();
        } else {
            if (!StringUtils.isEmpty(fileInfo.getSortType())) {
                example.setOrderByClause(fileInfo.getSortField() + " " + fileInfo.getSortType());
            }
        }
        return RestApiResponse.ok(new PageInfo<>(fileInfoMapper.selectByExample(example)));
    }
}
